package com.huanghuai.retail.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huanghuai.retail.common.R;
import com.huanghuai.retail.dto.StoreCheckDto;
import com.huanghuai.retail.entity.*;
import com.huanghuai.retail.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.huanghuai.retail.utils.RetailConstant.CHECK_PEOPLE;

/**
 * 仓库盘点
 *
 * @author guilong
 * @date 2023/05/03
 */
@RestController
@Api(tags = "仓库盘点模块说明")
@RequestMapping("/storeCheck")
@Slf4j
public class StoreCheckController {

    @Resource
    private StoreCheckService storeCheckService;
    @Resource
    private StoreCheckDetailService detailService;
    @Resource
    private InformationService informationService;
    @Resource
    private EmployeeServer employeeServer;
    @Resource
    private StorageService storageService;
    @Resource
    private TypeService typeService;

    /**
     * 新增盘点记录
     *
     * @param storeCheckDto 商店检查dto
     * @return {@link R}<{@link String}>
     */
    @ApiOperation("新增盘点记录接口")
    @PostMapping("/save")
    public R<String> saveCheck(@RequestBody StoreCheckDto storeCheckDto) {
        boolean res = storeCheckService.saveCheckAndDetails(storeCheckDto);
        if (res)
            return R.success("盘点记录添加成功!");
        return R.error("盘点记录添加失败");
    }

    /**
     * 分页查询仓库盘点
     *
     * @param page      页面
     * @param pageSize  页面大小
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param ids        ids
     * @return {@link R}<{@link Page}<{@link SCheck}>>
     */
    @ApiOperation("查询盘点记录接口")
    @GetMapping("/page")
    public R<Page> pageStoreCheck(Integer page, Integer pageSize,
                                  @ApiParam("开始时间 单位 毫秒 非必须") @RequestParam(value = "startTime", required = false) Long startTime,
                                  @ApiParam("结束时间 单位 毫秒 非必须") @RequestParam(value = "endTime", required = false) Long endTime,
                                  @ApiParam("仓库id 非必须") @RequestParam(value = "storageId", required = false) String storageIds,
                                  @ApiParam("经手人id 非必须") @RequestParam(value = "checkPerson", required = false) Long checkPerson,
                                  @ApiParam("盘点记录标号(id) 非必须") @RequestParam(value = "checkCode", required = false) String ids,
                                  @ApiParam("盘点记录经手人(id) 非必须") @RequestParam(value = "checkPeopleids", required = false) String checkPeopleids) {
        if(page==null||page<1)
            page = 1;
        if(pageSize==null || pageSize<1)
            pageSize = 5;
        Date startDate =null;
        Date endDate=null;
        if(startTime != null){
            startDate = new Date(startTime);
        }
        if(endTime != null){
            endDate = new Date(endTime);
        }

        List<Long> StringToLongList=null;
        if(storageIds!=null && !storageIds.isEmpty()){
            List<String>strings = Arrays.asList(storageIds.split(","));
            StringToLongList = new ArrayList<>();
            for (String s : strings) {
                StringToLongList.add(Long.valueOf(s));
            }
        }

        List<Long> longIds = null;
        if(ids!=null && !ids.isEmpty()){
            List<String> stringIds = Arrays.asList(ids.split(","));
             longIds = new ArrayList<>();
            for (String s : stringIds) {
                longIds.add(Long.valueOf(s));
            }
        }
        List<Long> checkPeople = null;
        if(checkPeopleids!=null && !checkPeopleids.isEmpty()){
            List<String> stringPeoples = Arrays.asList(checkPeopleids.split(","));
            checkPeople = new ArrayList<>();
            for (String s : stringPeoples) {
                checkPeople.add(Long.valueOf(s));
            }
        }


        // 所有商品信息
        List<PInformation> listInformation = informationService.list();
        // 所有盘点人信息
        LambdaQueryWrapper<Employee> employeeQueryWrapper = new LambdaQueryWrapper<>();
        employeeQueryWrapper.eq(Employee::getCategoryId,CHECK_PEOPLE);
        List<Employee> listCheckPeople = employeeServer.list(employeeQueryWrapper);
        // 所有仓库信息
        List<Storage> listStorage = storageService.list();
        // 所有商品类别信息
        List<PType> listTypeName = typeService.list();


        log.info("盘点记录查询分页：");
        // 1、构建分页构建器对象
        Page<SCheck> pageInfo = new Page<>(page, pageSize);
        Page<StoreCheckDto> dtoPage = new Page<>();
        // 2、创建条件查询对象
        LambdaQueryWrapper<SCheck> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(longIds!=null,SCheck::getId,longIds)
                .in(StringToLongList!=null,SCheck::getStorageId,StringToLongList)
                .in(checkPeople!=null,SCheck::getCheckPerson,checkPeople)
                .eq(checkPerson!=null,SCheck::getCheckPerson,checkPerson)
                .ge(startDate!=null,SCheck::getDate,startDate)
                .le(endDate != null,SCheck::getDate,endDate)
                .orderByDesc(SCheck::getDate);  // 根据时间降序
        storeCheckService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<SCheck> records = pageInfo.getRecords();
        List<StoreCheckDto> list = null;

        list = records.stream().map((item)->{
            StoreCheckDto storeCheckDto = new StoreCheckDto();
            BeanUtils.copyProperties(item, storeCheckDto);

            // 查询详细信息
            LambdaQueryWrapper<SCheckDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(item.getId()!=null,SCheckDetail::getCheckId,item.getId());
            List<SCheckDetail> list1 = detailService.list(lambdaQueryWrapper);

            // 给具体商品添加详细信息
            for(SCheckDetail i: list1){
                PInformation pInformation = null;
                String typeName=null;
                for(PInformation p:listInformation){
                    if(p.getId() == i.getProductId()){
                        pInformation = p;
                        break;
                    }
                }
                i.setPInformation(pInformation);
                for(PType p: listTypeName){
                    if(p.getId() == pInformation.getTypeId()){
                        typeName = p.getNameTwo();
                        break;
                    }
                }
                i.setProductTypeName(typeName);
            }
            storeCheckDto.setDetails(list1);

            // 添加经手人名称
            for(Employee e:listCheckPeople){
                if(e.getId() == item.getCheckPerson()){
                    storeCheckDto.setPeopleName(e.getName());
                    break;
                }
            }
            // 添加仓库名字
            for(Storage s:listStorage){
                if(s.getId() == item.getStorageId()){
                    storeCheckDto.setStoreName(s.getStorageName());
                    break;
                }
            }

            return storeCheckDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

}
